package com.cjh.wechat.core.controller;

import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cjh.wechat.commom.type.MessType;
import com.cjh.wechat.commom.vo.ChatRecordVo;
import com.cjh.wechat.commom.vo.PageVo;
import com.cjh.wechat.core.service.ChatRecordService;

@Controller
@RequestMapping("/chatrecord")
public class ChatRecordController
{
    @Resource
    private ChatRecordService chatRecordService;
    private static final int  PAGE_SIZE = 10;
    
    // 获取聊天记录
    @ResponseBody
    @RequestMapping(value = "/getRecord", method = RequestMethod.GET)
    public PageVo getRecord(int page, String myId, String friendId, String groupId, String type)
    {
        // 好友聊天记录
        if (type.equals(MessType.FRIEND.value))
        {
            // 获取好友聊天记录
            int total = chatRecordService.getFriendRecordNum(myId, friendId);
            List<ChatRecordVo> chatRecords = chatRecordService.getFriendRecord(myId, friendId, page, PAGE_SIZE);
            return buildPageVo(total, chatRecords);
        }
        // 群组聊天记录
        else
        {
            // 获取群组聊天记录
            int total = chatRecordService.getGroupRecordNum(groupId);
            List<ChatRecordVo> chatRecords = chatRecordService.getGroupRecord(groupId, page, PAGE_SIZE);
            return buildPageVo(total, chatRecords);
        }
    }
    
    private PageVo buildPageVo(int total, List<ChatRecordVo> chatRecords)
    {
        PageVo pageVo = new PageVo();
        if (total == 0)
        {
            pageVo.setPages(1);
        }
        else
        {
            pageVo.setPages(total % PAGE_SIZE == 0 ? total / PAGE_SIZE : total / PAGE_SIZE + 1);
        }
        pageVo.setData(chatRecords);
        return pageVo;
    }
}
